﻿//load required components from google visualization API
google.load('visualization', '1', { 'packages': ['corechart'] });


//define object to perform ELBMonitor functions
function AlarmList(listUrl, alarmDataUrl, refreshLengthMilliseconds, graphContainerId, alarmListData) {
    //set configurable options on this instance
    this.ListUrl = listUrl;
    this.AlarmDataUrl = alarmDataUrl;
    this.RefreshLengthMilliseconds = refreshLengthMilliseconds;
    this.graphContainerId = graphContainerId;
    this.alarms = [];
    this.RefreshAsync();

}



//options for elb traffic day-comparison graph
AlarmList.prototype.AlarmChartOptions = function (maxValue, minValue) {
    return {
        areaOpacity: 0.1,
        curveType: "function",
        isStacked: false,
        legend: "none",
        axisTitlesPosition: 'none',
        backgroundColor: 'white',
        chartArea: { left: 50, top: 0, width: "100%", height: "75%" },
        hAxis: { textStyle: { color: 'black'} },
        vAxis: { textStyle: { color: 'black'} },
        colors: ['red', 'green', 'blue', 'black'],
        series: { 0: { areaOpacity: 0.0, lineWidth: 4} },
        vAxis: { viewWindowMode: 'explicit', viewWindow: {min: minValue, max: maxValue} }
    };
};

AlarmList.prototype.RefreshAsync = function () {


    //self-reference for callbacks
    var instance = this;
    var data = null;

    $.ajax({
        url: this.ListUrl,
        type: 'POST',
        dataType: 'json',
        error: function (error) {
            alert(error);
        },
        success: function (result) {
            //set data


            //get reference to alarm list
            var graphContainer = $('#' + instance.graphContainerId);

            //clear content
            //graphContainer.html('');

            //rebuild content
            for (var j in result) {
                var alarm = result[j];
                //find matching element
                var alarmMatch = jQuery.grep(instance.alarms, function (a) { return a.Arn === alarm.Arn; });
                if (alarmMatch.length === 0) {
                    //add to alarm list
                    instance.alarms.push(alarm);
                    //if doesn't exist, setup container, display info
                    graphContainer.append("<div id='" + alarm.Arn + "' class='alarm'><h2>" + alarm.Name + "</h2><div id='" + alarm.Arn + "-chart' class='chart'>&nbsp;</div></div>");
                    //load graph data async
                    instance.LoadGraphForAlarmAsync(alarm.Name, alarm.Threshold, alarm.Arn + "-chart");
                }
            }



        }
    });
};

AlarmList.prototype.LoadGraphForAlarmAsync = function (alarmArn, threshold, graphContainerId) {

    //self-reference for callbacks
    var instance = this;
    var data = ({ alarmArn: alarmArn});

    $.ajax({
        url: this.AlarmDataUrl,
        type: 'POST',
        data: data,
        dataType: 'json',
        error: function (error) {
            alert('error getting data for alarm ' + alarmArn + '. Error:' + error);
        },
        success: function (result) {
            //set ELB request data
            instance.LoadTodayYesterdayLastWeekTwoWeeksChartFromJson(graphContainerId, result, threshold);
        }
    });

};

//function to displaya graph for an alarm
AlarmList.prototype.LoadTodayYesterdayLastWeekTwoWeeksChartFromJson = function (graphContainerId, dataItems, threshold) {
    //initialise data table
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'Date');
    data.addColumn('number', 'threshold');
    data.addColumn('number', '1wk');
    data.addColumn('number', 'ydy');
    data.addColumn('number', 'tdy');


    //add rows for each data item we have
    data.addRows(dataItems.length);

    //parse data, setting value for each cell as we find them
    for (var j in dataItems) {
        data.setValue(parseInt(j), 0, dataItems[j].Date); //set category column (date)
        data.setValue(parseInt(j), 1, threshold); //set threshold line
        //set value for each data line
        for (var k in dataItems[j].Data) {
            data.setValue(parseInt(j), parseInt(k) + 2, dataItems[j].Data[k] == 0 ? null : dataItems[j].Data[k]);
        }

    }

    //what should the min and max value be?
    var todayRange = data.getColumnRange(4);
    var minValue = (threshold<todayRange.min) ? threshold : todayRange.min;
    var maxValue = (threshold>todayRange.max) ? threshold : todayRange.max;
    maxValue = maxValue * 1.1;

    //draw new data to chart
    var chart = new google.visualization.AreaChart(document.getElementById(graphContainerId));
    chart.draw(data, this.AlarmChartOptions(maxValue,minValue));
};